package com.aiti.lulian.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.bo.CustomerFollowUpRecordBo;
import com.aiti.lulian.entity.CustomerFollowUpRecord;
import com.aiti.lulian.entity.CustomerManagement;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CustomerFollowUpRecordMapper;
import com.aiti.lulian.mapper.CustomerManagementMapper;
import com.aiti.lulian.service.ICustomerFollowUpRecordService;
import com.aiti.lulian.vo.CustomerFollowUpRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CustomerFollowUpRecordServiceImpl extends BaseSerivceImpl<CustomerFollowUpRecordMapper, CustomerFollowUpRecord> implements ICustomerFollowUpRecordService {

    private final CustomerFollowUpRecordMapper baseMapper;

    /** 远程调用获取用户信息 */
    private final CloudShowManagerSubService cloudShowManagerSubService;

    /***/
    private final CustomerManagementMapper customerManagementMapper;

    /**
     * 查询客户的跟进记录
     * @param bo 前端传入的参数
     * @return 跟进的记录
     */
    @Override
    public Map<String,Object> queryCustomerList(Page<CustomerFollowUpRecord> page,CustomerFollowUpRecordBo bo) {
        Map<String,Object> returnResult=  new HashMap<>();

        List<CustomerFollowUpRecordVo> customerFollowUpRecords = baseMapper.selectCustomPage(page,bo);
        List<CustomerFollowUpRecordVo> list = new ArrayList<>();

        //获取到查询的数据中是客户信息的Id
        Map<String, Map<String, String>> userIdToRealNameMap = new HashMap<>();

        if(StringUtils.equals(bo.getRecordType(),"1")){
            List<String> userId = customerFollowUpRecords.stream()
                    .filter(item -> StringUtils.equals(item.getRecordType(), "1"))
                    .map(CustomerFollowUpRecordVo::getBaseCreateBy)
                    .collect(Collectors.toList());
            Message usersInfo = cloudShowManagerSubService.getUsersInfo(userId);
            if(Objects.equals(usersInfo.getCode(), MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("获取用户信息失败");
            }
            userIdToRealNameMap = (Map<String, Map<String, String>>)usersInfo.getObj();
        }

        for(CustomerFollowUpRecordVo temp : customerFollowUpRecords){
            CustomerFollowUpRecordVo tempVo = CustomerFollowUpRecordVo.builder()
                    .baseId(temp.getBaseId())
                    .content(temp.getContent())
                    .build();
            //设置用户名称
            if(StringUtils.equals(temp.getRecordType(),"1")){
                Map<String, String> stringStringMap = userIdToRealNameMap.get(temp.getBaseCreateBy());
                if(stringStringMap != null){
                    tempVo.setCustomerName(stringStringMap.get("realname"));
                }
            }
            tempVo.setBaseCreateTime(temp.getBaseCreateTime());
            list.add(tempVo);
        }
        returnResult.put("rows",list);
        return returnResult;
    }

    /**
     * 新增跟进记录
     *
     * @param bo 参数
     */
    @Override
    public boolean addFollowUpRecord(CustomerFollowUpRecordBo bo) {
        CustomerFollowUpRecord record = new CustomerFollowUpRecord();
        BeanUtils.copyProperties(bo,record);
        if(record.getFollowUpTime() == null){
            //如果跟进时间是空的，则现在的时候就是跟进时间
            record.setFollowUpTime(DateUtil.date());
        }
        record.setBaseCreateTime(DateUtil.date());
        record.setBaseUpdateTime(DateUtil.date());
        int rows = baseMapper.insert(record);
        return rows > 0;
    }

    /**
     * 查询某个记录的详情
     *
     * @param bo 参数
     * @return 结果
     */
    @Override
    public CustomerFollowUpRecordVo queryCustomerFollowUpRecordDetail(CustomerFollowUpRecordBo bo) {
        LambdaQueryWrapper<CustomerFollowUpRecord> lqw = buildQueryWrapper(bo);
//        CustomerFollowUpRecord customerFollowUpRecord = baseMapper.selectOne(lqw);
        CustomerFollowUpRecord customerFollowUpRecord = baseMapper.selectCustomerFollowUpRecordByBaseId(bo.getBaseId());
        CustomerFollowUpRecordVo vo = new CustomerFollowUpRecordVo();
        if(customerFollowUpRecord != null){
            BeanUtils.copyProperties(customerFollowUpRecord,vo);
            //远程调用获取客户名称,如果这个值是1的时候才会是客户
//            if(StringUtils.equals(vo.getRecordType(),"1")){
//                LuLianEnterprise luLianEnterprise = luLianEnterpriseMapper.selectById(vo.getEnterpriseId());
//                if(luLianEnterprise != null){
//                    vo.setCustomerName(luLianEnterprise.getBaseName());
//                }
//            }else{
//                //走到这个分支就是需要查询商机的ID
//                CommunicateInfo communicateInfo = communicateInfoMapper.selectById(vo.getCustomerId());
//                if(communicateInfo != null){
//                    vo.setCustomerName(communicateInfo.getProductName());
//                }
//            }
            System.out.println("====>"  + customerFollowUpRecord);
            CustomerManagement customerManagement = customerManagementMapper.selectById(customerFollowUpRecord.getCustomerId());
            if(customerManagement != null){
                vo.setEnterpriseName(customerManagement.getEnterpriseName());
            }

        }
        return vo;
    }

    /**
     ////                CommunicateInfo communicateInfo
     * 更新根进记录
     *
     * @param bo 参数
     * @return 结果
     */
    @Override
    public boolean editCustomerFollowUpRecord(CustomerFollowUpRecordBo bo) {
        LambdaUpdateWrapper<CustomerFollowUpRecord> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(CustomerFollowUpRecord::getBaseId,bo.getBaseId());
//        lqw.eq(CustomerFollowUpRecord::getRecordType,bo.getRecordType());
//        lqw.eq(CustomerFollowUpRecord::getCustomerId,bo.getCustomerId());

        lqw.set(CustomerFollowUpRecord::getLinkMan,bo.getLinkMan());
        lqw.set(CustomerFollowUpRecord::getFollowUpTime,bo.getFollowUpTime());
        lqw.set(CustomerFollowUpRecord::getFollowUpType,bo.getFollowUpType());
        lqw.set(CustomerFollowUpRecord::getFollowUpType,bo.getFollowUpStage());
        lqw.set(CustomerFollowUpRecord::getContent,bo.getContent());
        lqw.set(CustomerFollowUpRecord::getBaseUpdateTime,LocalDateTime.now());

        int rows = baseMapper.update(null, lqw);
        return rows > 0;
    }

    @Override
    public boolean deleteShangJiFollowUpRecord(CustomerFollowUpRecordBo bo) {
        int rows = baseMapper.deleteById(bo.getBaseId());
        return rows > 0;
    }

    @Override
    public List<CustomerFollowUpRecordVo> getCustomerFollowUpRecordList(Page<CustomerFollowUpRecord> page, CustomerFollowUpRecordBo bo) {
        //查询当前用户角色
        Message userRoleMessage = cloudShowManagerSubService.getRoleByUserId(bo.getBaseCreateBy());
        if (userRoleMessage == null) {
            throw new RuntimeException("获取角色信息失败");
        } else if (! userRoleMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
            throw new RuntimeException("查询用户角色失败");
        } else {
            String roleIds = (String) userRoleMessage.getObj();
            if (roleIds == null) {
                throw new RuntimeException("查询用户角色为空");
            }
            //判断该用户是否为企业管理员
            boolean enterpriseAdmin = StringUtils.containsAny(roleIds, "043ea2e3e02c4aa591df1f83e65069bc", "8836c75af939406a9f41128826f6d8b3");
            bo.setEnterpriseAdmin(enterpriseAdmin);

            //查询该用户是否为部门负责人及其所属部门
            if(! enterpriseAdmin){
                Message userInfoMessage = cloudShowManagerSubService.getUserInfo(bo.getBaseCreateBy());
                if (userInfoMessage == null) {
                    throw new RuntimeException("获取用户信息失败");
                } else if (! userInfoMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                    throw new RuntimeException("查询用户信息失败");
                } else {
                    Object obj = userInfoMessage.getObj();
                    if (obj == null) {
                        throw new RuntimeException("查询用户为空");
                    }
                    ObjectMapper mapper = new ObjectMapper();
                    Map userInfoMap = mapper.convertValue(obj, Map.class);
                    String deptPermission = (String) userInfoMap.get("deptPermission");
                    String deptId = (String) userInfoMap.get("deptId");
                    bo.setDeptPermission(deptPermission);
                    bo.setDeptId(deptId);

                    //若为部门负责人，则获取其部门下所有子部门数据
                    if (StrUtil.equals(deptPermission, "1")) {
                        Message getSubDeptMessage = cloudShowManagerSubService.getSubDeptByDeptId(deptId);
                        if (getSubDeptMessage == null) {
                            throw new RuntimeException("获取子部门数据失败");
                        } else if (! getSubDeptMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                            throw new RuntimeException("查询子部门数据失败");
                        } else {
                            //获取到子部门以","分割的形式
                            String deptIds = (String) getSubDeptMessage.getObj();
                            if (deptIds == null) {
                                throw new RuntimeException("查询子部门数据为空");
                            }
                            List<String> deptIdList = new ArrayList<>(Arrays.asList(deptId));
                            if (StrUtil.isNotBlank(deptIds)) {
                                deptIdList.addAll(Arrays.asList(deptIds.split(",")));
                            }
                            bo.setDeptIdList(deptIdList);
                        }
                    }
                }
            }
        }
        return baseMapper.selectCustomerFollowUpRecordListPage(page, bo);
    }

    @Override
    public Message deleteCustomerFollowUpRecord(String[] baseIds) {
        List<String> strings = Arrays.asList(baseIds);
        this.baseMapper.deleteBatchIds(strings);
        return Message.success("删除成功");
    }

    /**
     * 构建基础的查询规则
     * @param bo 参数
     * @return 查询规则
     */
    private LambdaQueryWrapper<CustomerFollowUpRecord> buildQueryWrapper(CustomerFollowUpRecordBo bo) {
        LambdaQueryWrapper<CustomerFollowUpRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getBaseId()),CustomerFollowUpRecord::getBaseId,bo.getBaseId());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomerId()), CustomerFollowUpRecord::getCustomerId, bo.getCustomerId());
        lqw.eq(StringUtils.isNotBlank(bo.getFollowUpType()), CustomerFollowUpRecord::getFollowUpType, bo.getFollowUpType());
        lqw.orderByDesc(CustomerFollowUpRecord::getFollowUpTime);
        return lqw;
    }
}
